package test.com.ai.yc.portal.web.htmlconvert;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterProperties;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName: DocToHtmlConverter
 * @Description:
 * @Author: qiaowenxuan
 * @Date: 2024-12-11 15:09
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/context/core-context.xml"})
public class DocToHtmlConverter {

    @Test
    public void DocToHtmlConverterTest() {
        try {
            String docPath = "path/to/your/document.doc";
            InputStream fis = this.getClass().getClassLoader().getResourceAsStream("toHTML.doc");
            StringBuilder htmlContent = convertDocToHtml(fis);
            System.out.println("最终输出：：：");
            System.out.println(htmlContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static StringBuilder convertDocToHtml(InputStream fis) throws IOException {
        StringBuilder htmlBuilder = new StringBuilder();
        HWPFDocument document = new HWPFDocument(fis);
        Range range = document.getRange();

        htmlBuilder.append("<html><head>")
                .append("<meta charset=\"UTF-8\">")
                .append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")
                .append("<style>body { font-family: Arial, sans-serif; }") // 这里默认使用Arial
                .append("p { margin: 0 0 1em 0; line-height: 1.5; }")
                .append("span.forInput { text-decoration: underline; font-weight: normal; color: black;border: 1px dashed black; padding: 5px; }")
                .append("@page { size: A4; margin: 1cm; }")
                .append("</style></head><body>");

        for (int paraIndex = 0; paraIndex < range.numParagraphs(); paraIndex++) {
            Paragraph paragraph = range.getParagraph(paraIndex);
            String paragraphText = paragraph.text().trim();

            if (!paragraphText.isEmpty() || paragraphText.equals("\n") || paragraphText.equals("\r")) {
                int indentLevel = paragraph.getIndentFromLeft();

                // 处理字体样式和大小
                CharacterRun run = paragraph.getCharacterRun(0); // 获取第一个字符的样式
                String fontFamily = run.getFontName();
                int fontSize = run.getFontSize() / 2; // 字体大小
                boolean isBold = run.isBold();
                boolean isItalic = run.isItalic();

                htmlBuilder.append("<p style=\"text-indent:").append(indentLevel).append("px;")
                        .append("font-family:").append(fontFamily).append(";")
                        .append("font-size:").append(fontSize).append("pt;")
                        .append(isBold ? "font-weight:bold;" : "")
                        .append(isItalic ? "font-style:italic;" : "")
                        .append("\">");

                // 处理文本中的下划线
                int start;
                for (int i = 0; i < paragraphText.length(); i++) {
                    char currentChar = paragraphText.charAt(i);

                    if (currentChar == '_') {
                        start = i;
                        while (i < paragraphText.length() && paragraphText.charAt(i) == '_') {
                            i++;
                        }
                        String underlineText = paragraphText.substring(start, i);
                        htmlBuilder.append("<span class=\"forInput\">")
                                .append(underlineText)
                                .append("</span>");
                        i--;
                    } else {
                        htmlBuilder.append(currentChar);
                    }
                }

                htmlBuilder.append("</p>");
            } else {
                htmlBuilder.append("<p>&nbsp;</p>");
            }
        }

        htmlBuilder.append("</body></html>");
        return htmlBuilder;
    }

    public static StringBuilder convertDocToHtmlCanUse(InputStream fis) throws IOException {
        StringBuilder htmlBuilder = new StringBuilder();

        HWPFDocument document = new HWPFDocument(fis);
        Range range = document.getRange();

        htmlBuilder.append("<html><head><style>")
                .append("body { font-family: Arial, sans-serif; }")
                .append("p { margin: 0 0 1em 0; line-height: 1.5; }")
                .append("span.forInput { text-decoration: underline; font-weight: normal; color: black; }")
                .append("@page { size: A4; margin: 1cm; }")
                .append("</style></head><body>");

        for (int paraIndex = 0; paraIndex < range.numParagraphs(); paraIndex++) {
            Paragraph paragraph = range.getParagraph(paraIndex);
            String paragraphText = paragraph.text().trim();

            if (!paragraphText.isEmpty() || paragraphText.equals("\n") || paragraphText.equals("\r")) {
                int indentLevel = paragraph.getIndentFromLeft();
                htmlBuilder.append("<p style=\"text-indent:").append(indentLevel).append("px;\">");

                int start;
                for (int i = 0; i < paragraphText.length(); i++) {
                    char currentChar = paragraphText.charAt(i);

                    if (currentChar == '_') {
                        start = i;
                        while (i < paragraphText.length() && paragraphText.charAt(i) == '_') {
                            i++;
                        }
                        String underlineText = paragraphText.substring(start, i);
                        htmlBuilder.append("<span class=\"forInput\">")
                                .append(underlineText)
                                .append("</span>");
                        i--;
                    } else {
                        htmlBuilder.append(currentChar);
                    }
                }

                htmlBuilder.append("</p>");
            } else {
                htmlBuilder.append("<p>&nbsp;</p>");
            }
        }

        htmlBuilder.append("</body></html>");
        return htmlBuilder;
    }

    public static StringBuilder convertDocToHtml22(InputStream fis) throws IOException {
        StringBuilder htmlBuilder = new StringBuilder();

        HWPFDocument document = new HWPFDocument(fis);
        Range range = document.getRange();

        htmlBuilder.append("<html><head><style>")
                .append("body { font-family: Arial, sans-serif; }")
                .append("p { margin: 0; padding: 0; }")
                .append("span.forInput { text-decoration: underline; font-weight: normal; color: black; }") // 定义下划线区域的样式
                .append("@page { size: A4; margin: 1cm; }") // A4纸大小，1cm边距
                .append("</style></head><body>");

        // 遍历文档中的段落
        for (int paraIndex = 0; paraIndex < range.numParagraphs(); paraIndex++) {
            Paragraph paragraph = range.getParagraph(paraIndex);
            String paragraphText = paragraph.text();

            htmlBuilder.append("<p>");

            // 遍历段落中的每个字符，按字符进行拆分
            int start = 0;  // 起始位置
            for (int i = 0; i < paragraphText.length(); i++) {
                char currentChar = paragraphText.charAt(i);

                if (currentChar == '_') {
                    // 找到下划线区域，记录起始位置
                    start = i;
                    while (i < paragraphText.length() && paragraphText.charAt(i) == '_') {
                        i++; // 继续找到结束位置
                    }
                    String underlineText = paragraphText.substring(start, i);
                    htmlBuilder.append("<span class=\"forInput\">")
                            .append(underlineText)
                            .append("</span>");
                    i--; // 因为循环中 i 会多增加一次，调整回来
                } else {
                    // 非下划线字符，直接插入
                    htmlBuilder.append(currentChar);
                }
            }

            htmlBuilder.append("</p>");
            //System.out.println(htmlBuilder.toString());
        }
        htmlBuilder.append("</body></html>");
        return htmlBuilder;
    }


    public static String convertDocToHtml11(InputStream fis) throws IOException {
        StringBuilder htmlBuilder = new StringBuilder();

        HWPFDocument document = new HWPFDocument(fis);
        Range range = document.getRange();

        htmlBuilder.append("<html><head><style>")
                .append("body { font-family: Arial, sans-serif; }")
                .append("@page { size: A4; margin: 1cm; }")
                .append("</style></head><body>");

        // 遍历文档的段落
        for (int paraIndex = 0; paraIndex < range.numParagraphs(); paraIndex++) {
            String paragraphText = range.getParagraph(paraIndex).text();
            htmlBuilder.append("<p>");
            System.out.println("当前行的内容：："+paragraphText);

            // 获取该段落中的所有字符运行
            Paragraph paragraph = range.getParagraph(paraIndex);
            int numRuns = paragraph.numCharacterRuns();  // 获取段落中的字符运行数量

            // 遍历段落中的每个字符运行
            for (int runIndex = 0; runIndex < numRuns; runIndex++) {
                CharacterRun run = paragraph.getCharacterRun(runIndex);
                String runText = run.text();
                System.out.println("本行的第-"+(runIndex+1)+"个字符为：：："+runText);

                // 获取下划线样式代码
                //0：没有下划线
                //1：单下划线
                //2：双下划线
                //3：波浪下划线
                int underlineCode = run.getUnderlineCode();
                boolean hasUnderline = (underlineCode != 0);

                // 如果有下划线，包裹在 <span> 标签中
                if (hasUnderline) {
                    htmlBuilder.append("<span style=\"text-decoration: underline;\">")
                            .append(runText)
                            .append("</span>");
                } else {
                    htmlBuilder.append(runText);
                }
            }

            htmlBuilder.append("</p>");
        }

        htmlBuilder.append("</body></html>");
        return htmlBuilder.toString();
    }

}
